package com.example.sl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteExample {
    private static final String TAG = "SQLiteExample";
    private static SQLiteExample instance;
    private static final String DATABASE_NAME = "example_db";
    private static final String TABLE_NAME = "example_table";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_DATA = "data";

    private SQLiteDatabase database;
    private MySQLiteHelper helper;

    private SQLiteExample(Context context) {
        helper = new MySQLiteHelper(context, DATABASE_NAME, null, 1);
        database = helper.getWritableDatabase();
    }

    public static synchronized SQLiteExample getInstance(Context context){
        if(instance == null){
            instance = new SQLiteExample(context);
        }
        return instance;
    }

    public long addData(String data) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_DATA, data);
        long rowId = database.insert(TABLE_NAME, null, values);
        return rowId;
    }

    public Cursor getData() {
        String query = "SELECT * FROM " + TABLE_NAME;
        return database.rawQuery(query, null);
    }

    public void closeDb(){
        if(database!=null && database.isOpen()){
            database.close();
            database = null;
        }
    }

    /**
     * SQLiteOpenHelper是Android开发中用于管理SQLite数据库的一个类。它可以帮助你创建、升级和删除数据库。
     */
    private class MySQLiteHelper extends SQLiteOpenHelper {
        public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            String query = "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY," +
                    COLUMN_DATA + " TEXT" + ")";
            db.execSQL(query);
        }

        /**
         * SQLiteOpenHelper的onUpgrade方法在数据库版本号升级时被调用。
         * 当你改变你的数据库版本号，并且调用getWritableDatabase()或者getReadableDatabase()时，
         * 如果当前的版本号低于你设置的新的版本号，那么就会调用onUpgrade方法。
         * @param db The database.
         * @param oldVersion The old database version.
         * @param newVersion The new database version.
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // 可以在此处执行更新操作，例如添加新列或修改现有列的定义。
            if(newVersion > oldVersion){
                Log.d(TAG, "onUpgrade: 数据库升级");
            }
        }
    }
}